#include "Config.h"
#include "Common/Atoi.h"
#include "Common/CSVReader.h"
#include "wch/StringTokenizer.h"
#include "DataManager.h"
#include "Poker_CardRatio.h"
#include "Poker_RoomData.h"

Poker_CardRatios poker_CardRatios;
Poker_RoomDatas	 poker_RoomDatas;

bool DataManager::loadAllDatas()
{
	if ( !loadPokerCardRadio() )
	{
		fprintf( stderr, "loadPokerCardRadio Error !\n" );
		return false;
	}
	if ( !loadPokerRoomData() )
	{
		fprintf( stderr, "loadPokerRoomData Error !\n" );
		return false;
	}
	return true;
}

void DataManager::unLoadAllDatas()
{

}

bool DataManager::loadPokerCardRadio()
{
	CSVReader csv( "conf/cardRatio.csv" );
	csv.prepare( "id,ratio0,ratio1,ratio2,ratio3,ratio4,ratio5,ratio6" );
	while ( csv.next() )
	{
		Poker_CardRatio * cardRatio = new(std::nothrow) Poker_CardRatio();
		ASSERT( cardRatio != nullptr );
		cardRatio->_id = Atoi<UInt16>(csv[0]);
		UInt16 accuRatio = 0;
		for ( UInt8 i = 0; i < 7; ++ i )
		{
			UInt16 nAccuRatio = accuRatio + Atoi<UInt16>(csv[i+1]);
			for ( UInt16 r = accuRatio; r < nAccuRatio; ++ r )
				cardRatio->_ratio[r] = i;
			accuRatio = nAccuRatio;
		}
		poker_CardRatios.insert( std::make_pair( cardRatio->_id, cardRatio ) );
	}
	return true;
}


bool DataManager::loadPokerRoomData()
{
	CSVReader csv( "conf/room.csv" );
	csv.prepare( "id,name,bottomCast,lowCoin,highCoin,bets" );
	while ( csv.next() )
	{
		Poker_RoomData * data = new Poker_RoomData();
		data->_id = Atoi<UInt8>(csv[0]);
		data->_name = csv[1];
		data->_bottomCast = Atoi<UInt32>(csv[2]);
		data->_lowCoin = Atoi<UInt32>(csv[3]);
		data->_highCoin = Atoi<UInt32>(csv[4]);
		if ( data->_highCoin <= 0 )
			data->_highCoin = static_cast<UInt32>(-1);
		std::string bets = csv[5];
		wch::StringTokenizer tokenizer( bets, "|" );
		for ( size_t i = 0; i < tokenizer.count(); ++ i )
		{
			data->_bets.push_back( Atoi<UInt32>(tokenizer[i]) );
		}
		poker_RoomDatas.insert( std::make_pair( data->_id, data ) );
	}
	return true;
}

Poker_CardRatio * DataManager::getPokerCardRatio( UInt16 id )
{
	auto found = poker_CardRatios.find( id );
	return found == poker_CardRatios.end() ? nullptr : found->second;
}

Poker_RoomData * DataManager::getPokerRoomData( UInt8 id )
{
	auto found = poker_RoomDatas.find( id );
	return found == poker_RoomDatas.end() ? nullptr : found->second;
}